/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.rest;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.annotation.Log;
import me.zhengjie.constant.KwConstant;
import me.zhengjie.domain.KwExamRoom;
import me.zhengjie.exception.ParameterException;
import me.zhengjie.kwService.ExamRoomService;
import me.zhengjie.kwService.ExamTeacherService;
import me.zhengjie.pojo.dto.*;
import me.zhengjie.pojo.export.ExamRoomExport;
import me.zhengjie.pojo.vo.ExamRoomVo;
import me.zhengjie.service.KwExamRoomService;
import me.zhengjie.service.dto.KwExamRoomQueryCriteria;
import me.zhengjie.util.BaseResponse;
import me.zhengjie.util.KwUtils;
import me.zhengjie.util.ruoyiexcel.ExcelUtil;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @author LongYang
 * @website https://el-admin.vip
 * @date 2021-06-28
 **/
@RestController
@RequiredArgsConstructor
@Api(tags = "考场信息表前端控制器管理")
@RequestMapping("/api/kwExamRoom")
@Slf4j
public class KwExamRoomController {

    private final KwExamRoomService kwExamRoomService;
    private final ExamRoomService examRoomService;
    private final ExamTeacherService examTeacherService;
    private final KwUtils kwUtils;

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('kwExamRoom:list')")
    public void download(HttpServletResponse response, KwExamRoomQueryCriteria criteria) throws IOException {
        String identity = kwUtils.identity();
        if (Objects.equals(identity, KwConstant.DEPT)) return;
        kwExamRoomService.download(kwExamRoomService.queryAll(criteria), response);
    }

    @GetMapping
    @Log("查询考场信息表前端控制器")
    @ApiOperation("查询考场信息表前端控制器")
    @PreAuthorize("@el.check('kwExamRoom:list')")
    public ResponseEntity<Object> query(KwExamRoomQueryCriteria criteria, Pageable pageable) {
        Integer examId = criteria.getExamId();
        boolean permission = kwUtils.hasOtherPermission(Arrays.asList(examId));
        if (!permission) {
            return null;
        }
        return new ResponseEntity<>(kwExamRoomService.queryAll(criteria, pageable), HttpStatus.OK);
    }

    @Log("查询考场信息表前端控制器")
    @ApiOperation("查询考场信息表前端控制器")
    @GetMapping("/list")
    public ResponseEntity<Object> queryList(KwExamRoomQueryCriteria criteria, Pageable pageable) {
        return new ResponseEntity<>(kwExamRoomService.queryAll(criteria, pageable), HttpStatus.OK);
    }

    @PostMapping
    @Log("新增考场信息表前端控制器")
    @ApiOperation("新增考场信息表前端控制器")
    @PreAuthorize("@el.check('kwExamRoom:add')")
    public ResponseEntity<Object> create(@Validated @RequestBody KwExamRoom resources) {
        Integer examId = resources.getExamId();
        boolean permission = kwUtils.hasOtherPermission(Arrays.asList(examId));
        if (!permission) {
            throw new ParameterException("无权操作");
        }
        return new ResponseEntity<>(kwExamRoomService.create(resources), HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改考场信息表前端控制器")
    @ApiOperation("修改考场信息表前端控制器")
    @PreAuthorize("@el.check('kwExamRoom:edit')")
    public ResponseEntity<Object> update(@Validated @RequestBody KwExamRoom resources) {
        Integer examId = resources.getExamId();
        boolean permission = kwUtils.hasOtherPermission(Arrays.asList(examId));
        if (!permission) {
            throw new ParameterException("无权操作");
        }
        kwExamRoomService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log("删除考场信息表前端控制器")
    @ApiOperation("删除考场信息表前端控制器")
    @PreAuthorize("@el.check('kwExamRoom:del')")
    @DeleteMapping
    public ResponseEntity<Object> delete(@RequestBody Integer[] ids) {
        kwExamRoomService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }


    /*--------------------------------------------------------------------------------*/
    @ApiOperation("查询考场信息及其对应的考试信息、教室信息")
    @PostMapping("/get-kwExamRoom")
    @PreAuthorize("@el.check('kwExamRoom:getKwExamRoom')")
    public BaseResponse getKwExamRoom(@RequestBody @NotNull Integer id) {
        try {
            ExamRoomVo examRoomVo = examRoomService.findOneById(id);
            return BaseResponse.ok(examRoomVo);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("查询考场信息及其对应的考试信息、教室信息接口：" + e.getMessage());
            return BaseResponse.failed("查询失败：" + e.getMessage());
        }
    }

    @ApiOperation("新增考场信息及教室占用信息")
    @PostMapping("/save")
    @PreAuthorize("@el.check('kwExamRoom:save')")
    public BaseResponse saveExamRoom(@RequestBody @Validated ExamRoomDto dto) {
        Integer examId = dto.getExamId();
        boolean permission = kwUtils.hasOtherPermission(Arrays.asList(examId));
        if (!permission) {
            throw new ParameterException("无权操作");
        }
        try {
            return examRoomService.saveExamRoom(dto);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("新增考场信息及教室信息接口：" + e.getMessage());
            return BaseResponse.failed("新增失败：" + e.getMessage());
        }
    }

    @ApiOperation("给考场随机分配监考教师")
    @PostMapping("/random")
    @PreAuthorize("@el.check('kwExamRoom:random')")
    public BaseResponse random(@RequestBody @Validated ExamRoomRandomDto dto) {
        String identity = kwUtils.identity();
        if (Objects.equals(identity, KwConstant.DEPT)) throw new ParameterException("无权操作");
        examRoomService.random(dto);
        return BaseResponse.ok();
    }

    @ApiOperation("清除选中考场分配的监考教师")
    @PutMapping("/clear")
    @PreAuthorize("@el.check('kwExamRoom:clear')")
    public BaseResponse clear(@RequestBody @Validated ExamRoomClearDto dto) {
        String identity = kwUtils.identity();
        if (Objects.equals(identity, KwConstant.DEPT)) throw new ParameterException("无权操作");
        examRoomService.clear(dto);
        return BaseResponse.ok();
    }


    @ApiOperation("查询出所有本场考试未被分配的监考教师")
    @PostMapping("/findPage")
    @PreAuthorize("@el.check('kwExamRoom:findPage')")
    public BaseResponse findPage(@RequestBody @Validated ExamRoomFindPageTearcherDto dto) {
        return BaseResponse.ok(examRoomService.findPage(dto));
    }

    @ApiOperation("查询出所有本场考试未被分配的监考教师")
    @PostMapping("/findPageList")
    public BaseResponse findPageList(@RequestBody @Validated ExamRoomFindPageTearcherDto dto) {
        return BaseResponse.ok(examRoomService.findPage(dto));
    }

    @ApiOperation(value = "手动给考场分配监考教师", notes = "有考场id则把这个监考教师分配给该考场，无考场id则移除这个监考教师原来的考场")
    @PostMapping("/manual")
    @PreAuthorize("@el.check('kwExamRoom:manual')")
    public BaseResponse manual(@RequestBody @Validated ExamRommManualDto dto) {
        String identity = kwUtils.identity();
        if (Objects.equals(identity, KwConstant.DEPT)) throw new ParameterException("无权操作");
        examRoomService.manual(dto);
        return BaseResponse.ok();
    }


    @ApiImplicitParams({
            @ApiImplicitParam(name = "examId", value = "考试id", required = true),
            @ApiImplicitParam(name = "examRoomId", value = "考场id", required = true)
    })
    @ApiOperation("查询出在这个考试考场的监考教师")
    @GetMapping("/getExamTeachers")
    public BaseResponse getExamTeachers(
            @RequestParam("examId") @NotNull Integer examId,
            @RequestParam("examRoomId") @NotNull Integer examRoomId) {
        return BaseResponse.ok(examRoomService.getExamTeachers(examId, examRoomId));
    }

    @ApiOperation("考场导入模板下载")
    @GetMapping("/template")
    @PreAuthorize("@el.check('kwExamRoom:template')")
    public void importKwExamRoom(HttpServletResponse response) throws Exception {
        ExcelUtil<ExamRoomExport> excelUtil = new ExcelUtil<>(ExamRoomExport.class);
        excelUtil.importTemplateExcel(response, "考场信息模板");
    }

    @ApiOperation("考场导入")
    @PostMapping("/ruoyiImport")
    @PreAuthorize("@el.check('kwExamRoom:ruoyiImport')")
    public BaseResponse ruoYiImport(@RequestParam(value = "file") MultipartFile file, @RequestParam("examId") Integer examId) {
        boolean permission = kwUtils.hasOtherPermission(Arrays.asList(examId));
        if (!permission) {
            throw new ParameterException("无权操作");
        }
        if (file.isEmpty()) {
            return BaseResponse.failed("导入了空文件");
        }
        String fileName = file.getResource().getFilename();
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        System.out.println("后缀名:" + suffix);
        if (!"xls".equals(suffix) && !"xlsx".equals(suffix)) {
            return BaseResponse.failed("请导入xls，xlsx文件");
        }
        ExcelUtil<ExamRoomExport> util = new ExcelUtil<>(ExamRoomExport.class);
        try {
            List<ExamRoomExport> rooms = util.importExcel(file.getInputStream());
            if (rooms.isEmpty()) {
                return BaseResponse.failed("导入文件为空");
            }
            examRoomService.saveImportList(rooms, examId);
            return BaseResponse.ok("导入成功");
        } catch (Exception e) {
            e.printStackTrace();
            return BaseResponse.failed("导入失败：" + e.getMessage());
        }
    }

    @ApiOperation("导出该考试考场下的教师")
    @PostMapping("/ruoyiExport")
    @PreAuthorize("@el.check('kwExamRoom:ruoyiExport')")
    public BaseResponse export(HttpServletResponse response, @RequestBody @Validated ExamRoomExportDto dto) throws Exception {
        Integer examId = dto.getExamId();
        boolean permission = kwUtils.hasOtherPermission(Arrays.asList(examId));
        if (!permission) {
            throw new ParameterException("无权操作");
        }
        try {
            return examRoomService.export(response, dto);
        } catch (Exception e) {
            e.printStackTrace();
            return BaseResponse.failed("导出失败：" + e.getMessage());
        }
    }


}